package com.jdjc.suject.domin.service.impl;

import com.alibaba.fastjson.JSON;
import com.jdjc.subject.common.entity.PageResult;
import com.jdjc.subject.common.enums.IsDeletedFlagEnum;
import com.jdjc.subject.common.util.IdWorkerUtil;
import com.jdjc.subject.common.util.LoginUtil;
import com.jdjc.subject.infra.basic.entity.*;
import com.jdjc.subject.infra.basic.service.SubjectEsService;
import com.jdjc.subject.infra.basic.service.SubjectInfoService;
import com.jdjc.subject.infra.basic.service.SubjectLabelService;
import com.jdjc.subject.infra.basic.service.SubjectMappingService;
import com.jdjc.subject.infra.rpc.UserRPC;
import com.jdjc.suject.domin.convert.SubjectInfoConverter;
import com.jdjc.suject.domin.entity.SubjectInfoBO;
import com.jdjc.suject.domin.entity.SubjectOptionBO;
import com.jdjc.suject.domin.handler.subject.SubjectTypeHandler;
import com.jdjc.suject.domin.handler.subject.SubjectTypeHandlerFactory;
import com.jdjc.suject.domin.redis.RedisConfig;
import com.jdjc.suject.domin.redis.RedisUtil;
import com.jdjc.suject.domin.service.SubjectInfoDomainService;
import com.jdjc.suject.domin.service.SubjectLikedDomainService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


@Service
@Slf4j
public class SubjectInfoDomainServiceImpl implements SubjectInfoDomainService {
    @Resource
    private SubjectInfoService subjectInfoService;
    @Resource
    private SubjectTypeHandlerFactory subjectTypeHandlerFactory;
    @Resource
    private SubjectMappingService subjectMappingService;
    @Resource
    private SubjectLabelService subjectLabelService;
    @Resource
    private SubjectEsService subjectEsService;
    @Resource
    private UserRPC userRPC;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private SubjectLikedDomainService subjectLikedDomainService;

    private static final String RANK_KEY="subject_rank";
    @Autowired
    private RedisConfig redisConfig;

    /**
     * 新增题目
     * @param subjectInfoBO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(SubjectInfoBO subjectInfoBO) {
        if (log.isInfoEnabled()){
            log.info("SubjectInfoDomainServiceImpl：add:BO:{}", subjectInfoBO);
        }
        //工厂加策略模式
        //一个工厂包含四种类型，根据传入的type自动映射选择怎么处理
        SubjectInfo subjectInfo = SubjectInfoConverter.INSTANCE.convertBOToInfo(subjectInfoBO);
        subjectInfo.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        subjectInfoService.insert(subjectInfo);
        //
        SubjectTypeHandler handler = subjectTypeHandlerFactory.getHandler(subjectInfo.getSubjectType());
        subjectInfoBO.setId(subjectInfo.getId());
        handler.add(subjectInfoBO);
        List<Integer> categoryIds = subjectInfoBO.getCategoryIds();
        List<Integer> labelIds = subjectInfoBO.getLabelIds();
        List<SubjectMapping> mappingList=new LinkedList<>();
        categoryIds.forEach(categoryId -> {
            labelIds.forEach(labelId -> {
                SubjectMapping subjectMapping = new SubjectMapping();
                subjectMapping.setSubjectId(subjectInfo.getId());
                subjectMapping.setCategoryId(Long.valueOf(categoryId));
                subjectMapping.setLabelId(Long.valueOf(labelId));
                subjectMapping.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
                mappingList.add(subjectMapping);
            });
        });
        subjectMappingService.batchInsert(mappingList);
        //同步到es
        SubjectInfoEs subjectInfoEs=new SubjectInfoEs();
        //利用自定义的雪花算法工具类生成docid
        subjectInfoEs.setDocId(new IdWorkerUtil(1,1,1).nextId());
        subjectInfoEs.setSubjectId(subjectInfo.getId());
        subjectInfoEs.setSubjectAnswer(subjectInfoBO.getSubjectAnswer());
        subjectInfoEs.setCreateTime(new Date().getTime());
        subjectInfoEs.setCreateUser("小小");
        subjectInfoEs.setSubjectName(subjectInfo.getSubjectName());
        subjectInfoEs.setSubjectType(subjectInfo.getSubjectType());
        subjectEsService.insert(subjectInfoEs);
        //redis放入zadd计入排行榜
        //每出一道题，就往key里放入loginId，并且出题数加一
        redisUtil.addScore(RANK_KEY, LoginUtil.getLoginId(),1);
    }

    /**
     * 分页查询题目列表
     * @param subjectInfoBO
     * @return
     */
    @Override
    public PageResult<SubjectInfoBO> getSubjectPage(SubjectInfoBO subjectInfoBO) {
        PageResult<SubjectInfoBO> pageResult = new PageResult<>();
        pageResult.setPageNo(subjectInfoBO.getPageNo());
        pageResult.setPageSize(subjectInfoBO.getPageSize());
        int start = (subjectInfoBO.getPageNo() - 1) * subjectInfoBO.getPageSize();
        SubjectInfo subjectInfo = SubjectInfoConverter.INSTANCE.convertBOToInfo(subjectInfoBO);
        int count=subjectInfoService.countByCondition(subjectInfo,subjectInfoBO.getCategoryId()
                ,subjectInfoBO.getLabelId());
        if (count==0){
            return pageResult;
        }
        List<SubjectInfo> subjectInfoList=subjectInfoService.queryPage(subjectInfo,subjectInfoBO.getCategoryId()
                ,subjectInfoBO.getLabelId(),start,subjectInfoBO.getPageSize());
        List<SubjectInfoBO> subjectInfoBOS = SubjectInfoConverter.INSTANCE.InfoListToBOList(subjectInfoList);
        subjectInfoBOS.forEach(info -> {
            SubjectMapping subjectMapping = new SubjectMapping();
            subjectMapping.setSubjectId(info.getId());
            List<SubjectMapping> mappingList = subjectMappingService.queryLabelId(subjectMapping);
            List<Long> labelIds = mappingList.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());
            List<SubjectLabel> labelList = subjectLabelService.batchQueryById(labelIds);
            List<String> labelNames = labelList.stream().map(SubjectLabel::getLabelName).collect(Collectors.toList());
            info.setLabelName(labelNames);
        });
        pageResult.setRecords(subjectInfoBOS);
        pageResult.setTotal(count);
        return pageResult;
    }

    /**
     * 查询题目信息
     * @param subjectInfoBO
     * @return
     */
    @Override
    public SubjectInfoBO querySubjectInfo(SubjectInfoBO subjectInfoBO) {
        SubjectInfo subjectInfo = subjectInfoService.queryById(subjectInfoBO.getId());
        SubjectTypeHandler handler = subjectTypeHandlerFactory.getHandler(subjectInfo.getSubjectType());
        SubjectOptionBO optionBO = handler.query(subjectInfo.getId().intValue());

       /* log.info("optionBO:{}", optionBO);
        SubjectInfoBO infoBO = SubjectInfoConverter.INSTANCE.convertOptionAndInfoToBO(optionBO,subjectInfo);
        log.info("infoBO:{}", infoBO);*/
        SubjectInfoBO infoBO=SubjectInfoConverter.INSTANCE.InfoToBO(subjectInfo);
        infoBO.setSubjectAnswer(optionBO.getSujectAnswer());
        infoBO.setOptionList(optionBO.getOptionList());

        SubjectMapping subjectMapping=new SubjectMapping();
        subjectMapping.setSubjectId(subjectInfo.getId());
        subjectMapping.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        List<SubjectMapping> mappingList = subjectMappingService.queryLabelId(subjectMapping);
        List<Long> labelIdList = mappingList.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());

        List<SubjectLabel> labelList = subjectLabelService.batchqueryById(labelIdList);
        List<String> lableNameList = labelList.stream().map(SubjectLabel::getLabelName).collect(Collectors.toList());

        infoBO.setLabelName(lableNameList);
        //当前题目是否用户被点赞
        infoBO.setLiked(subjectLikedDomainService.isLiked(subjectInfoBO.getId().toString(),LoginUtil.getLoginId()));
        infoBO.setLikedCount(subjectLikedDomainService.getLikedCount(subjectInfoBO.getId().toString()));
        //获取上一题和下一题的题目id
        assembelSubjectCursor(subjectInfoBO,infoBO);

        return infoBO;
    }

    /**
     * 获取上一题和下一题的题目id
     * @param subjectInfoBO
     * @param infoBO
     */
    private void assembelSubjectCursor(SubjectInfoBO subjectInfoBO,SubjectInfoBO infoBO){
        Long categoryId = subjectInfoBO.getCategoryId();
        Long labelId = subjectInfoBO.getLabelId();
        Long subjectId = subjectInfoBO.getId();
        if (Objects.isNull(categoryId)||Objects.isNull(labelId)){
            return;
        }
        //查询下一题（1）和上一题（0）的题目id
        Long nextSubjectId=subjectInfoService.querySubjectIdCursor(subjectId,categoryId,labelId,1);
        infoBO.setNextSubjectId(nextSubjectId);
        Long lastSubjectId=subjectInfoService.querySubjectIdCursor(subjectId,categoryId,labelId,0);
        infoBO.setLastSubjectId(lastSubjectId);
    }

    /**
     * es全文检索
     * @param subjectInfoBO
     * @return
     */
    @Override
    public PageResult<SubjectInfoEs> getSubjectPageBySearch(SubjectInfoBO subjectInfoBO) {
        SubjectInfoEs subjectInfoEs=new SubjectInfoEs();
        subjectInfoEs.setKeyWord(subjectInfoBO.getKeyWord());
        subjectInfoEs.setPageNo(subjectInfoBO.getPageNo());
        subjectInfoEs.setPageSize(subjectInfoBO.getPageSize());

        return subjectEsService.querySubjectList(subjectInfoEs);
    }

    /**
     * 获取题目贡献榜单
     * @return
     */
    @Override
    public List<SubjectInfoBO> getContributeList() {
        //出题数前五名
        Set<ZSetOperations.TypedTuple<String>> typedTuples = redisUtil.rankWithScore(RANK_KEY, 0, 5);
        log.info("SubjectInfoDomainServiceImpl:getContributeList:typedTuples:{}", JSON.toJSONString(typedTuples));
        if (CollectionUtils.isEmpty(typedTuples)){
            return Collections.emptyList();
        }
        List<SubjectInfoBO> boList=new LinkedList<>();
        typedTuples.forEach(rank->{
            SubjectInfoBO subjectInfoBO=new SubjectInfoBO();
            subjectInfoBO.setSubjectCount(rank.getScore().intValue());
            UserInfo userInfo=userRPC.getUserInfo(rank.getValue());
            subjectInfoBO.setCreateUserAvatar(userInfo.getCreateUserAvatar());
            boList.add(subjectInfoBO);
        });
        return boList;
    }


}
